package com.elong.common.thrift;

import java.net.InetSocketAddress;

import org.apache.thrift.server.TServer.Args;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TSSLTransportFactory;
import org.apache.thrift.transport.TSSLTransportFactory.TSSLTransportParameters;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;

import com.elong.common.thrift.SharedService.Iface;


public class ThriftServer {

    public static ServerHandler handler;
    
    public static SharedService.Processor processor;
    
    public static void main(String[] args) {
        try {
            handler = new ServerHandler();
            processor = new SharedService.Processor<Iface>(handler);
            
            Runnable simple = new Runnable() {
                
                @Override
                public void run() {
                    simple(processor);
                }
            };
            new Thread(simple).run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void simple(SharedService.Processor processor){
        try {
            TServerTransport serverTransport = new TServerSocket(new InetSocketAddress("127.0.0.1", 9090));
            TServer server = new TSimpleServer(new Args(serverTransport).processor(processor));
            
            //use this for a multithreaded server
            //TServer server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor));
            System.out.println("starting the simple server");
            server.serve();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void secure(SharedService.Processor processor){
        try {
            /*
             * Use TSSLTransportParameters to setup the required SSL parameters. In this example
             * we are setting the keystore and the keystore password. Other things like algorithms,
             * cipher suites, client auth etc can be set. 
             */
            TSSLTransportParameters params = new TSSLTransportParameters();
            TServerTransport serverTransport = TSSLTransportFactory.getServerSocket(9091, 0, null, params);
            TServer server = new TSimpleServer(new Args(serverTransport).processor(processor));
         // Use this for a multi threaded server
            // TServer server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor));

            System.out.println("Starting the secure server...");
            server.serve();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
